package com.app.couponsharelife.ui.main.me.team

import android.content.Context
import android.content.Intent
import android.text.InputFilter
import android.util.Log
import android.view.inputmethod.EditorInfo
import androidx.fragment.app.Fragment
import com.ali.auth.third.ui.context.CallbackContext
import com.alibaba.baichuan.trade.biz.login.AlibcLogin
import com.alibaba.baichuan.trade.biz.login.AlibcLoginCallback
import com.google.android.material.appbar.AppBarLayout
import com.app.couponsharelife.R
import com.app.couponsharelife.base.BaseActivity
import com.app.couponsharelife.data.bean.RemoteResultBean
import com.app.couponsharelife.data.bean.UserTeamInfoBean
import com.app.couponsharelife.data.remote.retrofit.RetrofitWorker
import com.app.couponsharelife.data.remote.retrofit.exception.OtherException
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.ui.adapter.ViewPagerAdapter
import com.app.couponsharelife.ui.view.ScaleTransitionPagerTitleView
import com.app.couponsharelife.utils.AppUtils
import com.app.couponsharelife.utils.CalendarReminderUtils
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_newteam.*
import net.lucode.hackware.magicindicator.ViewPagerHelper
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator
import java.util.HashMap

/**
 *Created by xct on 2019/3/19
 *Description:我的团推改版页面
 */
class NewTeamActivity:BaseActivity() {
    private var mAdapter: ViewPagerAdapter? = null
    private var mTitles = arrayListOf<String>()
    private var commonNavigator: CommonNavigator?=null
    private var mPagers = arrayListOf<Fragment>()
    override val viewLayoutId: Int
        get() = R.layout.activity_newteam

    override fun initViews() {
        AppUtils.initImmersionBar(this,false)
        newteam_ivClose.setOnClickListener {
            AppUtils.hideInputBoard(this,basetitle_edit)
            finish()
        }
        basetitle_edit.filters = arrayOf<InputFilter>(InputFilter.LengthFilter(12))
        basetitle_edit.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH){
                val keyWord=basetitle_edit.text.toString().trim()
                if (keyWord.isNotEmpty()){
                    val intent= Intent(this,TeamSearchListActivity::class.java)
                    intent.putExtra("KeyWord",keyWord)
                    startActivity(intent)
                }else{
                    showToastMsg("请输入搜索内容！")
                }
                true
            }else{
                false
            }
        }
        basetitle_imag_delete.setOnClickListener {
            //basetitle_edit.setText("")
            //loging()
            val startTime=System.currentTimeMillis()+100000
            CalendarReminderUtils.addCalendarEvent(this,"测试","测试秒杀商品提醒功能",startTime,0)
        }
        initViewPager()
        getData()
    }
    private fun logout() {
        val alibcLogin = AlibcLogin.getInstance()
        alibcLogin.logout(object :AlibcLoginCallback{
            override fun onSuccess(p0: Int) {
                Log.i("eeee", "退出成功！")
            }

            override fun onFailure(p0: Int, p1: String?) {

            }
        })
    }
    private fun loging(){
        val alibcLogin = AlibcLogin.getInstance()
        alibcLogin.showLogin(object : AlibcLoginCallback {
            override fun onSuccess(p0: Int) {
                //获取淘宝用户信息  https://oauth.taobao.com/authorize?response_type=token&client_id=25327447&state=1212&view=web
                Log.i("eeee", "授权成功:${AlibcLogin.getInstance().session} ")
            }

            override fun onFailure(p0: Int, p1: String?) {
                Log.i("eeee", "授权失败:${p1} ")
            }
        })
    }
    private fun initViewPager() {
        with(mTitles) {
            add("全部队员")
            add("直属队员")
            add("推荐队员")
        }
        with(mPagers) {
            add(NewTeamFragment.newInstance(""))
            add(NewTeamFragment.newInstance("DIRECTLY_UNDER"))
            add(NewTeamFragment.newInstance("RECOMMEND"))
        }
        mAdapter = ViewPagerAdapter(supportFragmentManager, mPagers, mTitles)
        newteam_mViewPager.adapter = mAdapter
        newteam_mViewPager.offscreenPageLimit = 3
        commonNavigator= CommonNavigator(this)
        commonNavigator!!.isAdjustMode=true
        commonNavigator!!.adapter=object : CommonNavigatorAdapter(){
            override fun getTitleView(p0: Context, p1: Int): IPagerTitleView {
                val colorTransitionPagerTitleView= ScaleTransitionPagerTitleView(p0,0.9f)
                colorTransitionPagerTitleView.normalColor = resources.getColor(R.color.black)
                colorTransitionPagerTitleView.textSize=16f
                colorTransitionPagerTitleView.paint.isFakeBoldText=true
                colorTransitionPagerTitleView.selectedColor = resources.getColor(R.color.red_f90)
                colorTransitionPagerTitleView.text = mTitles[p1]
                colorTransitionPagerTitleView.setOnClickListener { newteam_mViewPager.currentItem = p1 }
                return colorTransitionPagerTitleView
            }
            override fun getCount(): Int {
                return mTitles.size
            }
            override fun getIndicator(p0: Context?): IPagerIndicator? {
                val indicator= LinePagerIndicator(p0)
                indicator.mode= LinePagerIndicator.MODE_WRAP_CONTENT
                indicator.setColors(resources.getColor(R.color.act_main_bot_nav_select_text_color))
                return indicator
            }
        }
        newteam_mTabLayout.navigator=commonNavigator
        ViewPagerHelper.bind(newteam_mTabLayout, newteam_mViewPager)
        newteam_mAppBar.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { _, verticalOffset ->
            when {
                verticalOffset==0 -> {
                    AppUtils.initImmersionBar(this@NewTeamActivity,false)
                    newteam_ivClose.setImageResource(R.drawable.ic_back_white)
                }
                Math.abs(verticalOffset) >= newteam_mAppBar.totalScrollRange -> {
                    AppUtils.initImmersionBar(this@NewTeamActivity,true)
                    newteam_ivClose.setImageResource(R.drawable.ic_back_black)
                }
                else -> {

                }
            }
        })
    }
    private fun getData(){
        showProgressDialog("加载中...")
        val map= HashMap<String,String>()
        map["userId"] =AppUtils.getString(Contacts.USERID, "")
        RetrofitWorker.retrofitWorker.getUserTeamInfo(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object :DisposableObserver<RemoteResultBean<UserTeamInfoBean>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<UserTeamInfoBean>) {
                        dismissProgressDialog()
                        if (it.code==200&&it.data!=null){
                            newteam_tvTjName.text = String.format("推荐我的人：%s", it.data!!.parentNickName)
                            newteam_tvAllNumber.text = String.format("%s", it.data!!.directlyUnderCount + it.data!!.recommendCount)
                            newteam_tvZs.text = String.format("直属队员：%s", it.data!!.directlyUnderCount)
                            newteam_tvTj.text = String.format("推荐队员：%s", it.data!!.recommendCount)
                        }
                    }

                    override fun onError(e: Throwable) {
                        dismissProgressDialog()
                        if (e is OtherException){
                            showToastMsg(e.msg)
                        }else{
                            showToastMsg("网络加载出错了！")
                        }
                    }
                })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        CallbackContext.onActivityResult(requestCode, resultCode, data)
    }
    override fun onDestroy() {
        super.onDestroy()
        AppUtils.destroyImmersionBar(this)
    }
}